package com.jyl.gateway.watcher;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class RouterWatcher {

    @Value("${netty.router}")
    private String zkNettyRouter;

    private CuratorFramework curatorFramework;

    @Autowired
    public RouterWatcher(CuratorFramework curatorFramework) {
        this.curatorFramework = curatorFramework;
    }

    public void subscribeEvent() throws Exception {
        if(curatorFramework.checkExists().forPath(zkNettyRouter)==null){
            curatorFramework.create().forPath(zkNettyRouter);
        }

        NodeCache nodeCache = new NodeCache(curatorFramework,zkNettyRouter,false);
        NodeCacheListener cacheListener = new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                ChildData childData = nodeCache.getCurrentData();
                log.info("ZNode节点状态改变, path={}", childData.getPath());
                log.info("ZNode节点状态改变, data={}", new String(childData.getData(), "Utf-8"));
                log.info("ZNode节点状态改变, stat={}", childData.getStat());

            }
        };
        //TODO 持续监听
        nodeCache.getListenable().addListener(cacheListener);
//        nodeCache.start();
    }

}
